﻿using MongoDB.Driver;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using Sustainalytics.ESG.Entities;
using System.Linq;
using System.Threading.Tasks;

namespace Sustainalytics.ScreeningTool.Synchronization.Caches
{
    public class IndicatorTemplatesCache : DictionaryCache<string, string>
    {
        public string this[string code] => GetValueOrEmpty(code, string.Empty);
    }

    public class IndicatorTemplatesCacheLoader : ICacheLoader<IndicatorTemplatesCache>
    {
        private readonly IndicatorTemplatesCache cache;
        private readonly IMongoCollection<IndicatorTemplate> collection;

        public IndicatorTemplatesCacheLoader(
            IndicatorTemplatesCache cache,
            IMongoCollection<IndicatorTemplate> collection)
        {
            this.cache = cache;
            this.collection = collection;
        }

        public async Task LoadAsync(ClientFacingProduct clientFacingProduct)
        {
            var values = await collection
                .Find(_ => true)
                .Project(x => new { x.Number, x.Name })
                .SortBy(x => x.Number)
                .ToListAsync();

            var items = values.ToDictionary(x => x.Number, x => x.Name);

            cache.AddItems(items);
        }
    }
}
